package com.atguigu.gulimall.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.PrintWriter;

/**
 * 配置sentinel 错误的自定义返回数据
 */
@Configuration
public class SentinelConfig {
    public SentinelConfig() {
        GatewayCallbackManager.setBlockHandler(
                (serverWebExchange, throwable) -> {
                    // 网关限流了请求，就会调用此回调
                    R error = R.error(BizCodeEnume.TO_MANY_REQUEST);
                    String json = JSON.toJSONString(error);

                    // webflux
                    return ServerResponse
                            .ok()
                            .body(
                                    Mono.just(json),
                                    String.class
                            );
                }
        );
    }
}
